package main

import (
	"bytes"
	"crypto/sha1"
	"encoding/json"
	"fmt"
	"io"
	"io/ioutil"
	"math/rand"
	"net/http"
	"sort"
	"strings"

	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/net/ghttp"
	"github.com/tidwall/gjson"
)

const (
	token     = "wufly"
	APPID     = "wx2488810c3d62ef41"
	APPSECRET = "b05ad09f6f6bad3a08aa5424c7245e21"
)

func Hello2(r *ghttp.Request) {
	// 获取请求的参数
	timestamp := r.GetString("timestamp")
	nonce := r.GetString("nonce")
	// 获取签名
	signatureGen := makeSignature(timestamp, nonce)
	// 跟url传过来的签名对比
	signatureIn := r.GetString("signature")
	if signatureGen != signatureIn {
		fmt.Println("签名不正确")
		r.Response.Write("哈喽世界！")
	}
	r.Response.Write(r.GetString("echostr"))
}

func main() {
	s := g.Server()
	//s.SetPort(30082)
	s.Domain("wechat.wufly.cn").BindHandler("/", Hello2)
	//s.BindHandler("/", Hello2)
	//s.BindHandler("/access_token", GetAccessToken)
	//s.Domain("wechat.wufly.cn").BindHandler("/access_token", GetAccessToken)
	s.Domain("wechat.wufly.cn").BindHandler("/send", SendMsg)
	s.Run()
}

func makeSignature(timestamp, nonce string) string {
	// 将token、timestamp、nonce三个参数进行字典序排序
	sli := []string{token, timestamp, nonce}
	sort.Strings(sli)
	a := sha1.New()
	io.WriteString(a, strings.Join(sli, ""))
	return fmt.Sprintf("%x", a.Sum(nil))

}

// 获取access_token
func GetAccessToken() string {
	wechatRsp, err := http.Get(fmt.Sprintf("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s", APPID, APPSECRET))
	if err != nil {
		g.Log().Info("获取token出错")
	}
	defer func() {
		_ = wechatRsp.Body.Close()
	}()
	bodyC, _ := ioutil.ReadAll(wechatRsp.Body)
	fmt.Println(string(bodyC))
	return gjson.Get(string(bodyC), "access_token").String()
}

// 发送消息
func SendMsg(r *ghttp.Request) {
	song := make(map[string]interface{})
	filter := make(map[string]interface{})
	filter["is_to_all"] = true
	filter["tag_id"] = 2
	song["filter"] = filter
	text := make(map[string]interface{})
	text["content"] = "TEST"
	song["text"] = text
	song["msgtype"] = "text"
	song["clientmsgid"] = rand.Intn(10000)
	bytesData, err := json.Marshal(song)
	if err != nil {
		fmt.Println(err.Error())
		return
	}
	reader := bytes.NewReader(bytesData)
	client := &http.Client{}
	access_token := GetAccessToken()
	fmt.Println("access_token:", access_token)
	req, err := http.NewRequest("POST", "https://api.weixin.qq.com/cgi-bin/message/mass/sendall?access_token="+access_token, reader)
	if err != nil {
		// handle error
	}

	req.Header.Set("Content-Type", "application/json;charset=UTF-8")

	resp, err := client.Do(req)
	if err != nil {
		fmt.Println(err)
	}

	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		// handle error
		fmt.Println(11, err)
	}

	fmt.Println(string(body))
}
